<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>APM 监控 - RustCloud 仪表板</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
        }

        .nav {
            background: white;
            padding: 15px 0;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .nav ul {
            list-style: none;
            display: flex;
            gap: 30px;
        }

        .nav a {
            text-decoration: none;
            color: #333;
            font-weight: 500;
            padding: 10px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        .nav a:hover, .nav a.active {
            background-color: #667eea;
            color: white;
        }

        .apm-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .summary-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .summary-title {
            color: #667eea;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 10px;
            text-transform: uppercase;
        }

        .summary-value {
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .summary-unit {
            font-size: 14px;
            color: #666;
        }

        .performance-good { color: #10b981; }
        .performance-warning { color: #f59e0b; }
        .performance-poor { color: #ef4444; }

        .apm-tabs {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            overflow: hidden;
        }

        .tab-header {
            display: flex;
            background: #f8f9fa;
            border-bottom: 1px solid #e1e5e9;
        }

        .tab-button {
            padding: 15px 25px;
            background: none;
            border: none;
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.3s;
        }

        .tab-button.active {
            background: white;
            color: #667eea;
            border-bottom: 2px solid #667eea;
        }

        .tab-button:hover {
            background: #e9ecef;
        }

        .tab-content {
            padding: 20px;
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .bottleneck-item {
            background: #f8f9fa;
            border-left: 4px solid #ef4444;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 0 5px 5px 0;
        }

        .bottleneck-critical { border-left-color: #dc2626; }
        .bottleneck-high { border-left-color: #ef4444; }
        .bottleneck-medium { border-left-color: #f59e0b; }
        .bottleneck-low { border-left-color: #3b82f6; }

        .bottleneck-title {
            font-weight: 600;
            margin-bottom: 8px;
        }

        .bottleneck-description {
            color: #666;
            margin-bottom: 10px;
        }

        .bottleneck-recommendations {
            background: white;
            padding: 10px;
            border-radius: 5px;
        }

        .bottleneck-recommendations h4 {
            font-size: 14px;
            margin-bottom: 8px;
            color: #667eea;
        }

        .bottleneck-recommendations ul {
            padding-left: 20px;
        }

        .bottleneck-recommendations li {
            margin-bottom: 4px;
            font-size: 13px;
        }

        .chart-container {
            height: 300px;
            background: #f8f9fa;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
            margin: 20px 0;
        }

        .transaction-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .transaction-table th {
            background: #f8f9fa;
            padding: 12px;
            text-align: left;
            border-bottom: 2px solid #e1e5e9;
            font-weight: 600;
        }

        .transaction-table td {
            padding: 12px;
            border-bottom: 1px solid #f1f3f4;
        }

        .transaction-table tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }

        .status-success {
            background: #d1fae5;
            color: #065f46;
        }

        .status-error {
            background: #fee2e2;
            color: #991b1b;
        }

        .status-timeout {
            background: #fef3c7;
            color: #92400e;
        }

        .no-data {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .error-message {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .refresh-button {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin-bottom: 20px;
            transition: background-color 0.3s;
        }

        .refresh-button:hover {
            background: #5a67d8;
        }

        .slow-query-item {
            background: #fff7ed;
            border: 1px solid #fed7aa;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 5px;
        }

        .slow-query-title {
            font-weight: 600;
            color: #ea580c;
            margin-bottom: 5px;
        }

        .slow-query-time {
            font-size: 12px;
            color: #666;
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="container">
            <h1>🔧 APM 性能监控</h1>
        </div>
    </header>

    <nav class="nav">
        <div class="container">
            <ul>
                <li><a href="/">概览</a></li>
                <li><a href="/metrics">指标</a></li>
                <li><a href="/alerts">告警</a></li>
                <li><a href="/apm" class="active">APM</a></li>
                <li><a href="/health">健康检查</a></li>
            </ul>
        </div>
    </nav>

    <main class="container">
        <!-- 性能统计摘要 -->
        <div class="apm-summary">
            <div class="summary-card">
                <div class="summary-title">总事务数</div>
                <div class="summary-value" id="total-events">-</div>
                <div class="summary-unit">个事务</div>
            </div>
            
            <div class="summary-card">
                <div class="summary-title">平均响应时间</div>
                <div class="summary-value performance-good" id="avg-response-time">-</div>
                <div class="summary-unit">毫秒</div>
            </div>
            
            <div class="summary-card">
                <div class="summary-title">错误率</div>
                <div class="summary-value performance-good" id="error-rate">-</div>
                <div class="summary-unit">%</div>
            </div>
            
            <div class="summary-card">
                <div class="summary-title">慢查询数</div>
                <div class="summary-value" id="slow-queries">-</div>
                <div class="summary-unit">个查询</div>
            </div>
        </div>

        <button class="refresh-button" onclick="loadApmData()">🔄 刷新数据</button>

        <div id="error-container"></div>

        <!-- APM 标签页 -->
        <div class="apm-tabs">
            <div class="tab-header">
                <button class="tab-button active" onclick="switchTab('performance')">性能分析</button>
                <button class="tab-button" onclick="switchTab('bottlenecks')">瓶颈识别</button>
                <button class="tab-button" onclick="switchTab('transactions')">事务跟踪</button>
                <button class="tab-button" onclick="switchTab('slowqueries')">慢查询</button>
            </div>

            <!-- 性能分析标签页 -->
            <div class="tab-content active" id="performance-tab">
                <h3>性能趋势分析</h3>
                <div class="chart-container">
                    📈 响应时间趋势图 (待实现)
                </div>
                
                <h3>错误率分析</h3>
                <div class="chart-container">
                    📊 错误率分析图 (待实现)
                </div>
            </div>

            <!-- 瓶颈识别标签页 -->
            <div class="tab-content" id="bottlenecks-tab">
                <h3>系统瓶颈报告</h3>
                <div id="bottlenecks-container">
                    <div class="loading">正在分析系统瓶颈...</div>
                </div>
            </div>

            <!-- 事务跟踪标签页 -->
            <div class="tab-content" id="transactions-tab">
                <h3>最近事务记录</h3>
                <table class="transaction-table">
                    <thead>
                        <tr>
                            <th>服务名称</th>
                            <th>操作</th>
                            <th>状态</th>
                            <th>响应时间</th>
                            <th>开始时间</th>
                        </tr>
                    </thead>
                    <tbody id="transactions-tbody">
                        <tr>
                            <td colspan="5" class="loading">正在加载事务数据...</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 慢查询标签页 -->
            <div class="tab-content" id="slowqueries-tab">
                <h3>慢查询监控</h3>
                <div id="slowqueries-container">
                    <div class="loading">正在分析慢查询...</div>
                </div>
            </div>
        </div>
    </main>

    <script>
        let currentTab = 'performance';
        let apmStats = null;
        let bottlenecks = [];

        // 切换标签页
        function switchTab(tabName) {
            // 更新按钮状态
            document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');

            // 更新内容显示
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            document.getElementById(tabName + '-tab').classList.add('active');

            currentTab = tabName;

            // 根据当前标签页加载相应数据
            if (tabName === 'bottlenecks') {
                loadBottlenecks();
            } else if (tabName === 'transactions') {
                // TODO: 加载事务数据
            } else if (tabName === 'slowqueries') {
                // TODO: 加载慢查询数据
            }
        }

        // 加载 APM 数据
        async function loadApmData() {
            try {
                showLoading();
                const response = await fetch('/api/apm/stats');
                const result = await response.json();
                
                if (result.success) {
                    apmStats = result.data;
                    updateApmSummary();
                    hideError();
                } else {
                    showError('获取 APM 数据失败: ' + result.error);
                }
            } catch (error) {
                console.error('加载 APM 数据失败:', error);
                showError('无法连接到服务器');
            }
        }

        // 更新 APM 摘要
        function updateApmSummary() {
            if (!apmStats) return;

            document.getElementById('total-events').textContent = apmStats.total_events;
            
            const avgResponseTime = apmStats.avg_response_time;
            const avgElement = document.getElementById('avg-response-time');
            avgElement.textContent = avgResponseTime.toFixed(2);
            
            // 根据响应时间设置颜色
            avgElement.className = 'summary-value ' + getPerformanceClass(avgResponseTime, 100, 500);

            const errorRate = apmStats.error_rate;
            const errorElement = document.getElementById('error-rate');
            errorElement.textContent = errorRate.toFixed(2);
            
            // 根据错误率设置颜色
            errorElement.className = 'summary-value ' + getPerformanceClass(errorRate, 1, 5);

            document.getElementById('slow-queries').textContent = apmStats.slow_queries;
        }

        // 获取性能类别
        function getPerformanceClass(value, goodThreshold, poorThreshold) {
            if (value <= goodThreshold) {
                return 'performance-good';
            } else if (value <= poorThreshold) {
                return 'performance-warning';
            } else {
                return 'performance-poor';
            }
        }

        // 加载瓶颈数据
        async function loadBottlenecks() {
            try {
                const response = await fetch('/api/apm/bottlenecks');
                const result = await response.json();
                
                if (result.success) {
                    bottlenecks = result.data;
                    displayBottlenecks();
                } else {
                    showBottleneckError('获取瓶颈数据失败: ' + result.error);
                }
            } catch (error) {
                console.error('加载瓶颈数据失败:', error);
                showBottleneckError('无法连接到服务器');
            }
        }

        // 显示瓶颈信息
        function displayBottlenecks() {
            const container = document.getElementById('bottlenecks-container');
            
            if (bottlenecks.length === 0) {
                container.innerHTML = '<div class="no-data">✅ 暂未检测到系统瓶颈</div>';
                return;
            }

            container.innerHTML = bottlenecks.map(bottleneck => {
                const severityClass = 'bottleneck-' + bottleneck.severity.toLowerCase();
                const detectedTime = new Date(bottleneck.detected_at).toLocaleString();
                
                return `
                    <div class="bottleneck-item ${severityClass}">
                        <div class="bottleneck-title">
                            ${getBottleneckTypeIcon(bottleneck.bottleneck_type)} 
                            ${bottleneck.description}
                        </div>
                        <div class="bottleneck-description">
                            影响服务: ${bottleneck.affected_services.join(', ')} | 
                            检测时间: ${detectedTime}
                        </div>
                        <div class="bottleneck-recommendations">
                            <h4>优化建议:</h4>
                            <ul>
                                ${bottleneck.recommendations.map(rec => `<li>${rec}</li>`).join('')}
                            </ul>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 获取瓶颈类型图标
        function getBottleneckTypeIcon(type) {
            const icons = {
                'Cpu': '🔥',
                'Memory': '💾',
                'Network': '🌐',
                'DiskIo': '💿',
                'Database': '🗄️',
                'ExternalDependency': '🔗',
                'Algorithm': '⚡'
            };
            return icons[type] || '⚠️';
        }

        // 显示加载状态
        function showLoading() {
            // 在摘要卡片中显示加载状态
            document.querySelectorAll('.summary-value').forEach(el => {
                el.textContent = '-';
            });
        }

        // 显示错误
        function showError(message) {
            const errorContainer = document.getElementById('error-container');
            errorContainer.innerHTML = `<div class="error-message">❌ ${message}</div>`;
        }

        // 隐藏错误
        function hideError() {
            document.getElementById('error-container').innerHTML = '';
        }

        // 显示瓶颈错误
        function showBottleneckError(message) {
            const container = document.getElementById('bottlenecks-container');
            container.innerHTML = `<div class="error-message">❌ ${message}</div>`;
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadApmData();
            
            // 设置自动刷新（每30秒）
            setInterval(loadApmData, 30000);
        });
    </script>
</body>
</html>